import './style.css'
import { Button, Dropdown, Form, Input, Popconfirm, Radio, Select, Spin } from 'antd'
import { getItem, message, USERRESULT } from '@hs-admin/utils'
import { HsAdminAddProjects } from '@/components/global'
import { commonFormProps, commonInputProps, commonSelectProps } from '@/views/ShoppingCart/commonProps.ts'
import { useCallback, useEffect, useRef, useState } from 'react'
import {
  copyCommonScope,
  createCommonScope,
  createSubCommonScopeList,
  deleteOrderDraft,
  getAllShoppingOrderItems,
  getCommonScopeDraft,
  getCommonScopeList,
  getOrderDraft,
  getSubCommonScopeList,
  putOrderDraft,
  putCommonScopeName,
  putDraftOrderItem,
  submitTheShoppingOrder
} from '@/api/shoppingCart.ts'
import { useNavigate } from 'react-router-dom'
import DataBaseInfoModal from '@/views/ShoppingCart/components/DataBaseInfoModal.tsx'
import { getProjectInfor } from '@/api/developCenter/project.ts'
import ScopeCard, { useChooseCommonScopeType } from '@/views/ShoppingCart/components/ScopeCard.tsx'
import ChooseFieldModal from '@/views/ShoppingCart/components/ChooseFieldModal.tsx'

const kindItems = [
  {
    key: 'scope',
    label: (
      <div className="flex flex-col gap-4">
        <div className="text-xl">综合范围</div>
        <div>包括：产业范围、区域范围、园区范围</div>
      </div>
    )
  },
  {
    key: 'white-list',
    label: (
      <div className="flex flex-col gap-4">
        <div className="text-xl">企业白名单范围</div>
        <div>自动读本项目回流到白名单表中的企业范围</div>
      </div>
    ),
    disabled: true
  }
]

export const TimeOptions = [
  {
    label: '每天',
    value: 'daily'
  },
  {
    label: '每周',
    value: 'weekly'
  },
  {
    label: '每月',
    value: 'monthly'
  },
  {
    label: '每季',
    value: 'quarterly'
  },
  {
    label: '每年',
    value: 'yearly'
  },
  {
    label: '一次性',
    value: 'once'
  }
]

export const getTimeLabel = (value: string) => TimeOptions.find((it) => it.value === value)?.label ?? '--'

const CronItem = ({ value1, onChange1 }: { value1: string; onChange1: (value: string) => void }) => {
  return <Select {...commonSelectProps} value={value1} onChange={onChange1} options={TimeOptions} />
}

const rules = [
  {
    required: true
  }
]

const owner_id = getItem(USERRESULT)?.id

const SubmitShoppingOrder = () => {
  const refDataBaseInfo = useRef<any>()
  const refMapping = useRef<any>()
  const [form] = Form.useForm()

  const doSubmit = useRef(false)

  const [draftInfo, setDraftInfo] = useState({
    name: '',
    requirement_source: '',
    db_config_id: null as null | string,
    project_id: null as null | number,
    id: '',
    scope_id: null as null | string,
    update_frequency: '',
    update_frequency_values: [] as Array<string>
  })

  const [validateDatabase, setValidateDatabase] = useState({
    validateStatus: '',
    help: ''
  })

  const [projectMembers, setProjectMembers] = useState<Array<string>>([])

  const navigate = useNavigate()

  const [itemList, setItemList] = useState<
    Array<{
      table_name: string
      mapping_table_name: string
      id: string
      product_id: string
      update_frequency: 'default' | 'monthly' | 'weekly' | 'daily' | 'yearly' | 'once' | null
      sync_mode: 'whole' | 'incremental' | null
      update_frequency_values: Array<string>
      supports_whole_scope: boolean
      single_scope_id: string
    }>
  >([])

  const [loading, setLoading] = useState(false)

  const [tempOptions, setTempOptions] = useState<
    Array<{
      label: string
      value: string
    }>
  >([])

  const tempEvent = useRef((scopeId: string) => {
    console.log(scopeId)
  })

  const [tempName, setTempName] = useState('')

  const [myScopes, setMyScopes] = useState<
    Array<{
      label: string
      value: string
    }>
  >([])

  const [scopeInfo, setScopeInfo] = useState({
    name: '',
    id: '',
    type: '',
    white_list_token: '',
    draft: true
  })

  const commonScopeId = scopeInfo.draft ? '' : scopeInfo.id

  const { Component, openModal } = useChooseCommonScopeType()

  useEffect(() => {
    getCommonScopeList({
      page: 1,
      page_size: 9999,
      draft: false,
      owner_id
    }).then((res) => {
      setMyScopes(
        res.items.map((it) => ({
          label: it.name,
          value: it.id
        }))
      )
    })
  }, [])

  useEffect(() => {
    if (draftInfo.scope_id) {
      getCommonScopeDraft(draftInfo.scope_id).then((res) => {
        setScopeInfo(res)
        setTempName(res.name)
      })
      tempEvent.current(draftInfo.scope_id)
    } else {
      setScopeInfo({
        name: '',
        id: '',
        type: '',
        white_list_token: '',
        draft: true
      })
    }
  }, [draftInfo.scope_id])

  const updateScopeInfo = useCallback(() => {
    getCommonScopeDraft(draftInfo.scope_id).then((res) => {
      setScopeInfo(res)
    })
  }, [draftInfo.scope_id])

  const doSetItem = (value: any, item: any) => {
    putDraftOrderItem(item.id, draftInfo.id, {
      dst_tb_name: item.dst_tb_name,
      sync_mode: item.sync_mode,
      interval: value,
      column_mappings: item.column_mappings
    }).then(() => {
      getItems()
    })
  }

  const updateDraftInfo = async () => {
    try {
      const response = await getOrderDraft()
      const res = response.items[0]
      setDraftInfo({
        name: res.name,
        requirement_source: res.requirement_source,
        db_config_id: res.db_config_id,
        project_id: res.project_id,
        id: res.id,
        scope_id: res.scope_id,
        update_frequency: res.update_frequency,
        update_frequency_values: res.update_frequency_values
      })
      form.setFieldsValue(res)
    } catch {
      message.error('不存在草稿订单')
    }
  }

  useEffect(() => {
    if (draftInfo.project_id)
      getProjectInfor({
        id: draftInfo.project_id
      }).then((res2) => {
        setProjectMembers(res2.members.map((it) => it.name))
        setTempOptions([
          {
            label: res2.name,
            value: draftInfo.project_id
          }
        ])
      })
    else {
      setProjectMembers([])
    }
  }, [draftInfo.project_id])

  useEffect(() => {
    updateDraftInfo()
  }, [])

  const getItems = useCallback(() => {
    if (draftInfo.id) {
      setLoading(true)
      getAllShoppingOrderItems(draftInfo.id)
        .then((res) => {
          setItemList(res.items)
        })
        .finally(() => {
          setLoading(false)
        })
    }
  }, [draftInfo.id])

  const checkDataBase = useCallback(() => {
    if (!draftInfo.db_config_id) {
      setValidateDatabase({
        validateStatus: 'error',
        help: "'数据环境信息' 是必填字段"
      })
      return false
    } else {
      setValidateDatabase({
        validateStatus: '',
        help: ''
      })
      return true
    }
  }, [draftInfo.db_config_id])

  useEffect(() => {
    if (doSubmit.current) {
      checkDataBase()
    }
  }, [checkDataBase])

  useEffect(() => {
    getItems()
  }, [getItems])

  return (
    <div className="shopping-cart-wrapper">
      <div className="head-filter-part">
        <h2 className="flex justify-between">
          订单填写
          <div className="flex gap-4">
            <Popconfirm
              onConfirm={() => {
                deleteOrderDraft(draftInfo.id).then(() => {
                  message.success('删除成功')
                  navigate('/shoppingCart')
                })
              }}
              title="确认删除?">
              <Button>删除订单</Button>
            </Popconfirm>
            <Popconfirm
              title="订单提交后，不可增加数据项"
              onConfirm={() => {
                doSubmit.current = true
                form
                  .validateFields()
                  .then((values) => {
                    if (checkDataBase()) {
                      if (
                        itemList.every((item) => {
                          if (item.dst_tb_name) {
                            const required_column_mappings = item.column_mappings.filter((it) => it.is_required)
                            if (required_column_mappings.length) {
                              return required_column_mappings.every((it) => it.dst_col_name)
                            } else {
                              return true
                            }
                          }
                          return false
                        })
                      ) {
                        submitTheShoppingOrder(draftInfo.id, {
                          name: values.name,
                          source: values.source,
                          proj_id: values.proj_id
                        }).then(() => {
                          message.success('提交成功')
                          navigate('/shoppingOrderList')
                        })
                      } else {
                        message.error('“目标映射表名”或目标字段映射不完整')
                      }
                    }
                  })
                  .catch((e) => {
                    console.log(e)
                    checkDataBase()
                  })
              }}>
              <Button type="primary">提交订单</Button>
            </Popconfirm>
          </div>
        </h2>
        <div className="common-title-style py-4">
          <div className="shop-title">订单信息</div>
        </div>
        <Form
          form={form}
          {...commonFormProps}
          validateMessages={{
            required: "'${label}' 是必填字段"
          }}>
          <div className="grid grid-cols-2 gap-x-2 overflow-hidden">
            <Form.Item name="name" label="订单名称" rules={rules}>
              <Input
                {...commonInputProps()}
                onBlur={(e) => {
                  if (e.currentTarget.value)
                    putOrderDraft(draftInfo.id, {
                      ...draftInfo,
                      name: e.currentTarget.value
                    }).then(updateDraftInfo)
                }}
              />
            </Form.Item>
            <Form.Item name="requirement_source" label="需求来源" rules={rules}>
              <Select
                {...commonSelectProps}
                options={['产业大脑项目', '产业大脑SAAS', '金融数据服务项目'].map((it) => ({
                  label: it,
                  value: it
                }))}
                onChange={(value) => {
                  if (value)
                    putOrderDraft(draftInfo.id, {
                      ...draftInfo,
                      requirement_source: value
                    }).then(updateDraftInfo)
                }}
              />
            </Form.Item>
            <Form.Item name="project_id" label="关联项目名称" rules={rules}>
              <HsAdminAddProjects
                {...commonSelectProps}
                from="new"
                style={{ width: '100%' }}
                options={tempOptions}
                onChange={(pid) => {
                  if (pid) {
                    putOrderDraft(draftInfo.id, {
                      ...draftInfo,
                      project_id: pid
                    }).then(updateDraftInfo)
                  }
                }}
              />
            </Form.Item>
            <div className="grid grid-cols-4 gap-2 overflow-auto">
              <label htmlFor="project_members" className="text-right">
                项目成员:
              </label>
              <div className="col-span-3 flex gap-1">
                {projectMembers.length
                  ? projectMembers.map((it) => (
                      <span className="whitespace-nowrap" key={it}>
                        {it}
                      </span>
                    ))
                  : '--'}
              </div>
            </div>
            <Form.Item name="update_frequency" label="整体数据更新周期" rules={rules}>
              <Select
                value={draftInfo.update_frequency}
                options={TimeOptions}
                onChange={(value) => {
                  if (value === draftInfo.update_frequency) return
                  if (value) {
                    if (value !== draftInfo.update_frequency)
                      putOrderDraft(draftInfo.id, {
                        ...draftInfo,
                        update_frequency: value
                      }).then(updateDraftInfo)
                  }
                }}
              />
            </Form.Item>
            <Form.Item name="db_config_id" label="数据环境信息" required={true} {...validateDatabase}>
              <div
                onClick={() => {
                  refDataBaseInfo.current?.showModal()
                }}>
                {draftInfo.db_config_id ? (
                  <span className="text-green-400 hover:cursor-pointer">{'去编辑>>'}</span>
                ) : (
                  <span className="text-red-400 hover:cursor-pointer">{'去填写>>'}</span>
                )}
              </div>
            </Form.Item>
          </div>
        </Form>
        <div className="common-title-style py-4 gap-4">
          <div className="shop-title">整体范围选择</div>
          <Select
            className="min-w-32"
            value={commonScopeId}
            options={[
              {
                label: '创建整体范围',
                value: ''
              },
              {
                label: '我的整体范围',
                options: myScopes
              },
              {
                label: '项目整体范围',
                options: [
                  {
                    label: 'bb',
                    value: 'vv'
                  }
                ]
              }
            ]}
            onChange={(value) => {
              if (value === draftInfo.scope_id) return
              if (value) {
                if (value !== draftInfo.scope_id)
                  putOrderDraft(draftInfo.id, {
                    ...draftInfo,
                    scope_id: value
                  }).then(updateDraftInfo)
              } else {
                if (!scopeInfo.draft) {
                  putOrderDraft(draftInfo.id, {
                    ...draftInfo,
                    scope_id: null
                  }).then(updateDraftInfo)
                }
              }
            }}
          />
          <span className="whitespace-nowrap before:content-['*'] before:mr-0.5 before:text-red-500">范围名称:</span>
          <Input
            disabled={!scopeInfo.draft}
            value={tempName}
            onChange={(e) => {
              setTempName(e.currentTarget.value)
            }}
            onBlur={() => {
              if (tempName !== scopeInfo.name) {
                putCommonScopeName(scopeInfo.id, {
                  name: tempName
                }).then(() => {
                  setScopeInfo((pre) => ({
                    ...pre,
                    name: tempName
                  }))
                })
              }
            }}
          />
        </div>
        {draftInfo.scope_id && <ScopeCard scopeInfo={scopeInfo} callUpdate={updateScopeInfo} />}
        {scopeInfo.draft ? (
          <Dropdown
            menu={{
              items: kindItems,
              onClick: (item) => {
                switch (item.key) {
                  case 'scope':
                    if (draftInfo.scope_id) {
                      createSubCommonScopeList({
                        scope_id: draftInfo.scope_id
                      }).then(() => {
                        updateScopeInfo()
                        getSubCommonScopeList({
                          scope_id: draftInfo.scope_id,
                          page_size: 100,
                          page: 1
                        }).then((res2) => {
                          const subId = res2.items.at(-1).id
                          openModal(subId, updateScopeInfo)
                        })
                      })
                    } else {
                      createCommonScope({
                        name: scopeInfo.name ?? '',
                        type: 'specification',
                        order_id: draftInfo.id
                      }).then(() => {
                        tempEvent.current = (sid) =>
                          getSubCommonScopeList({
                            scope_id: sid,
                            page_size: 100,
                            page: 1
                          }).then((res2) => {
                            const subId = res2.items.at(-1).id
                            openModal(subId, updateScopeInfo)
                          })
                        updateDraftInfo()
                      })
                    }

                    break
                  case 'white-list':
                    break
                }
              }
            }}>
            <Button type="primary" className="w-full" ghost>
              添加范围
            </Button>
          </Dropdown>
        ) : (
          <Button
            type="primary"
            ghost
            onClick={() => {
              copyCommonScope(draftInfo.scope_id).then(updateDraftInfo)
            }}>
            修改以上范围
          </Button>
        )}
      </div>
      <div className="content-part">
        <div className="common-title-style py-4">
          <div className="shop-title">数据项映射信息</div>
        </div>
        <Spin spinning={loading}>
          <table className="w-full">
            <thead>
              <tr className="text-left">
                <th className="w-18% text-xl p2">数据项表名</th>
                <th className="w-18% text-xl p2">映射关系</th>
                <th className="w-10% text-xl p2">同步方式</th>
                <th className="w-18% text-xl p2">更新周期</th>
                <th className="w-12% text-xl p2">是否支持整体范围</th>
                <th className="w-18% text-xl p2">单独编辑范围</th>
              </tr>
            </thead>
            <tbody>
              {itemList.map((item) => (
                <tr key={item.id} className="border-y border-solid border-gray-100 border-x-none">
                  <td className="p2">{item.table_name}</td>
                  <td className="p2">
                    <div className="flex items-center"></div>
                    <span className={`p1 ${item.mapping_table_name ? 'bg-green-400/85' : 'bg-red-400/85'}`}>
                      {item.mapping_table_name ? '已' : '未'}配置
                    </span>
                    <Button
                      type="link"
                      onClick={() => {
                        refMapping.current?.showModal({
                          productId: item.product_id,
                          id: item.id,
                          tableName: item.table_name,
                          mappingTableName: item.mapping_table_name,
                          dbId: draftInfo.db_config_id
                        })
                      }}>
                      去配置
                    </Button>
                  </td>
                  <td className="p2">
                    <Select
                      {...commonSelectProps}
                      className="w-full"
                      value={item.sync_mode}
                      options={[
                        {
                          label: '增量同步',
                          value: 'incremental'
                        },
                        {
                          label: '全量同步',
                          value: 'whole'
                        }
                      ]}
                      onChange={(value) => {
                        putDraftOrderItem(item.id, draftInfo.id, {
                          dst_tb_name: item.dst_tb_name,
                          sync_mode: value,
                          interval: item.interval,
                          column_mappings: item.column_mappings
                        }).then(() => {
                          getItems()
                        })
                      }}
                    />
                  </td>
                  <td className="grid grid-cols-[auto_1fr] p2">
                    <Radio checked={!item.interval} onChange={() => doSetItem(null, item)}>
                      复用整体更新周期
                    </Radio>
                    <CronItem value1={item.interval} onChange1={(value) => doSetItem(value, item)} />
                  </td>
                  <td>
                    <span className={`p1 ${item.supports_whole_scope ? 'bg-green-400/85' : 'bg-red-400/85'}`}>
                      {item.supports_whole_scope ? '是' : '否'}
                    </span>
                  </td>
                  <td>
                    <div className="flex items-center">
                      <span className={`p1 ${item.single_scope_id ? 'bg-green-400/85' : 'bg-red-400/85'}`}>
                        {item.single_scope_id ? '已' : '未'}编辑
                      </span>
                      <Button type="link">编辑</Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Spin>
      </div>
      {Component}
      <DataBaseInfoModal
        ref={refDataBaseInfo}
        dbId={draftInfo.db_config_id}
        onOk={async (id) => {
          try {
            if (draftInfo.db_config_id !== id) {
              await putOrderDraft(draftInfo.id, {
                ...draftInfo,
                db_config_id: id
              }).then(updateDraftInfo)
              getItems()
            }
            return true
          } catch {
            return false
          }
        }}
      />
      <ChooseFieldModal ref={refMapping} updateList={getItems} />
    </div>
  )
}

export default SubmitShoppingOrder
